package edu.ecu.seng6270.goa.ropa;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JSpinner.DefaultEditor;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.table.AbstractTableModel;

import net.miginfocom.swing.MigLayout;

/**
 * GUI Panel allowing a user to create a Custom order
 */
public class AltCustomOrderPanel extends JPanel {

	ROPAMain parent;
	private static final long serialVersionUID = -2335098498729452402L;
	
	private Order myOrder;
	private JLabel moreDiscountsAlert;
	
	int numItemsInt;
	private JTable displayOrder;

	AltCustomOrderPanel(final ROPAMain parent) {
		super();
		this.parent = parent;
		numItemsInt = 1;

		this.setBackground(new Color(255, 255, 255));
		this.setLayout(new MigLayout("", "[grow]", "[grow][grow][grow][][][][][]"));

		JLabel lblCustomOrder = new JLabel("Custom Reprints");
		lblCustomOrder.setFont(new Font("Tahoma", Font.BOLD, 18));
		this.add(lblCustomOrder, "cell 0 0,alignx center");
		
		JLabel lblChooseOptionsAnd = new JLabel("Choose options and quantity, then click \"Add to Order\"");
		add(lblChooseOptionsAnd, "cell 0 1,alignx center");
		
		JLabel photoSizeLabel1 = new JLabel("Photo Size:");
		add(photoSizeLabel1, "flowx,cell 0 2,alignx center");
		
		myOrder = new Order(parent.getMyCustomerID());
		OrderTableModel otm = new OrderTableModel(myOrder);
		displayOrder = new JTable(otm);
		
		displayOrder.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  

		
		add(new JScrollPane(displayOrder), "flowx,cell 0 3,grow");
		
		JLabel orderSubtotalLabel = new JLabel("Order Subtotal:");
		add(orderSubtotalLabel, "flowx,cell 0 4,alignx center");
		
		JButton btnCancelOrder = new JButton("Cancel Order");
		btnCancelOrder.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				parent.cards.removeAll();
				parent.moveToCard("orderTypePanel");
			}
		});
		add(btnCancelOrder, "flowx,cell 0 5,alignx center");
		
		final JLabel orderSubtotal = new JLabel("$0.00");
		add(orderSubtotal, "cell 0 4,alignx center");
		
		final JComboBox photoSize1 = new JComboBox();
		add(photoSize1, "cell 0 2");
		photoSize1.setModel(new DefaultComboBoxModel(new String[] {"4x6", "5x7", "8x10"}));
		
		JLabel photoFinishLabel1 = new JLabel("Photo Finish:");
		add(photoFinishLabel1, "cell 0 2");
		
		final JComboBox photoFinish1 = new JComboBox();
		add(photoFinish1, "cell 0 2");
		photoFinish1.setModel(new DefaultComboBoxModel(new String[] {"Glossy", "Matte"}));
		
		JLabel processingTimeLabel1 = new JLabel("Processing Time:");
		add(processingTimeLabel1, "cell 0 2");
		
		final JComboBox processingTime1 = new JComboBox();
		add(processingTime1, "cell 0 2");
		processingTime1.setModel(new DefaultComboBoxModel(new String[] {"Next Day", "1 Hour"}));
		
		JLabel quantityLabel1 = new JLabel("Quantity:");
		add(quantityLabel1, "cell 0 2");
		
		final JSpinner quantity1 = new JSpinner();
		add(quantity1, "cell 0 2");
		quantity1.setModel(new SpinnerNumberModel(1, 1, 100, 1));
		final JFormattedTextField pqt = ((DefaultEditor) quantity1.getEditor()).getTextField();
		pqt.addKeyListener(new KeyListener() {
			
			@Override
			public void keyTyped(KeyEvent arg0) {
			}
			
			@Override
			public void keyReleased(KeyEvent arg0) {
				Integer spv = 0;
				try {
					spv = Integer.valueOf(pqt.getText());
				} catch (Exception e){
					spv = 1;
				}
				
				if (spv <= 1) {
					quantity1.setValue(1);
				}
				
				if (spv > 100) {
					quantity1.setValue(100);
				}
			}
			
			@Override
			public void keyPressed(KeyEvent arg0) {
			}

		});


		
		JLabel lblPhotoID = new JLabel("Photo ID:");
		add(lblPhotoID, "cell 0 2");
		
		final JComboBox cboPhotoID = new JComboBox();
		cboPhotoID.setModel(new DefaultComboBoxModel(new String[] {"Photo 1", "Photo 2", "Photo 3", "Photo 4", "Photo 5", "Photo 6", "Photo 7", "Photo 8", "Photo 9", "Photo 10"}));
		add(cboPhotoID, "cell 0 2");
					
		JButton btnAddToOrder = new JButton("Add to Order");
		btnAddToOrder.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				OrderItem oi = new OrderItem();
				oi.setMySize(photoSize1.getSelectedIndex()+1);
				oi.setMyFinish(photoFinish1.getSelectedIndex()+1);
				oi.setMyPTime(processingTime1.getSelectedIndex()+1);
				oi.setMyQuantity((Integer) quantity1.getValue());
				oi.setMyPhotoId(cboPhotoID.getSelectedIndex()+1);
								
				if (oi.getMyQuantity() > checkQuantitySpaceRemaining(myOrder)) {
					// Should show the error somewhere
					JOptionPane.showMessageDialog(parent.cards, "Sorry, no more than 100 reprints are allowed in an order.", "Maximum Order Quantity", JOptionPane.INFORMATION_MESSAGE);
					return;
				}
				/// Added by Pouyan////
				if (myOrder.CheckDuplicate(oi) != null) {
					OrderItem oitemp = new OrderItem();
					oitemp = myOrder.CheckDuplicate(oi);
					myOrder.myItemList.remove(oitemp);
					oi.setMyQuantity(oi.getMyQuantity()+oitemp.getMyQuantity());
					oitemp = null;
					JOptionPane.showMessageDialog(parent.cards,"This item was already on the list, we've added the quantity to the existing item.", "Item Duplicate", JOptionPane.INFORMATION_MESSAGE);
				}
				/// End of the things added by Pouyan////
				myOrder.insertOrderItem(oi);
				myOrder.calculateOrderPrice();
				displayOrder.updateUI();
				orderSubtotal.setText(String.format("$%.2f", myOrder.getNonDiscountedPrice()));
				if (myOrder.getNonDiscountedPrice() > 35) {
					moreDiscountsAlert.setVisible(true);
				} else {
					moreDiscountsAlert.setVisible(false);
				}
			}
		});
		add(btnAddToOrder, "cell 0 2");
		
		
		JButton btnRemoveSelectedRow = new JButton("Remove");
		btnRemoveSelectedRow.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
				try {
					int sr = displayOrder.getSelectedRow();
					
					if (sr >= 0) {
						myOrder.getMyItemList().remove(sr);
						myOrder.calculateOrderPrice();
						displayOrder.updateUI();
						orderSubtotal.setText(String.format("$%.2f", myOrder.getNonDiscountedPrice()));
						if (myOrder.getNonDiscountedPrice() > 35) {
							moreDiscountsAlert.setVisible(true);
						} else {
							moreDiscountsAlert.setVisible(false);
						}
					}
				} catch (Exception e) {
					// Ignore silently
				}
				
			}
		});
		add(btnRemoveSelectedRow, "cell 0 3,alignx trailing");
		
		JButton button = new JButton("Proceed to Checkout");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (myOrder.getMyItemList().size() == 0) {
					return;
				}
				if (myOrder.myItemList.size() == 1) {
					// JOptionPane.showMessageDialog(parent.cards,"You can order this features as Express Order",
					// "Save Money", JOptionPane.INFORMATION_MESSAGE);
					
					// See if there's only one item
					Object[] options = { "Yes, proceed to checkout", "Return to Order" };
					int n = JOptionPane.showOptionDialog(parent.cards,
							"This order is eligible for Express handling\nat a potentially lower price.\n\nWould you like to checkout anyway?",
							"Express Order Eligible", JOptionPane.YES_NO_OPTION,
							JOptionPane.QUESTION_MESSAGE, null, options,
							options[0]);

					if (n == JOptionPane.NO_OPTION) {
						// returning to order
						return;
					}
				}
				
				
				if (myOrder.myItemList.size() > 1) {
					// Loop through items to see if there's a mix of processing times
					Boolean hasNext = false;
					Boolean hasHour = false;
					for (OrderItem oi : myOrder.getMyItemList()) {
						if (oi.getMyPTime() == 1) {
							hasNext = true;
						} else {
							hasHour = true;
						}
					}
					if (hasNext && hasHour) {
						Object[] options = { "Yes, proceed to checkout", "Return to Order" };
						int n = JOptionPane.showOptionDialog(parent.cards,
								"Your order contains both Next Day and 1 Hour processing.\nYou may choose 1 Hour for all items at no additional charge.\n\nWould you like to checkout anyway?",
								"1 Hour Processing for All Prints?", JOptionPane.YES_NO_OPTION,
								JOptionPane.QUESTION_MESSAGE, null, options,
								options[0]);

						if (n == JOptionPane.NO_OPTION) {
							// returning to order
							return;
						}
					}
				}

				parent.setPendingOrder(myOrder);
				parent.moveToCard("checkoutPanel");

			}
		});
		
		add(button, "cell 0 5");
		
		moreDiscountsAlert = new JLabel("This order may be eligible for ADDITIONAL DISCOUNTS during checkout! ");
		moreDiscountsAlert.setForeground(new Color(0, 102, 0));
		moreDiscountsAlert.setFont(new Font("Tahoma", Font.BOLD, 10));
		add(moreDiscountsAlert, "cell 0 6,alignx center");
		moreDiscountsAlert.setVisible(false);
		
	}

	class OrderTableModel extends AbstractTableModel{
		
		private static final long serialVersionUID = 1L;
		private String[] colNames = {"Photo ID","Size","Finish","Processing Time","Quantity"};  

		Order mo;
		
		OrderTableModel(Order mo) {
			this.mo = mo;
		}

		@Override
		public int getColumnCount() {
			// TODO Auto-generated method stub
			return colNames.length;
		}
		
		@Override
		public String getColumnName(int arg0) {
			return colNames[arg0];
		}

		@Override
		public int getRowCount() {
			return mo.getMyItemList().size();
		}

		@Override
		public Object getValueAt(int rowNum, int colNum) {
			int vv;
			switch (colNum) {
			case 0:
				vv = mo.getMyItemList().get(rowNum).getMyPhotoId();
				return String.format("Photo ID: %d", mo.getMyItemList().get(rowNum).getMyPhotoId());
			case 1:												
				vv = mo.getMyItemList().get(rowNum).getMySize();
				switch (vv) {
					case 2:
						return "5x7";
					case 3:
						return "8x10";
					default:
						return "4x6";
				}
			case 2:
				vv = mo.getMyItemList().get(rowNum).getMyFinish();
				return (vv == 1) ? "Glossy" : "Matte";
			case 3:
				vv = mo.getMyItemList().get(rowNum).getMyPTime();
				return (vv == 1) ? "Next Day" : "1 Hour";
			default:
				return mo.getMyItemList().get(rowNum).getMyQuantity();
			}
		}
		
	}
	
	private int checkQuantitySpaceRemaining(Order myOrder) {
		int oq = 0;
		for (OrderItem oi : myOrder.getMyItemList()) {
			oq += oi.getMyQuantity();
		}
		return 100 - oq;
	}
	
}
